import csv
import json

import redis
from redis import Redis

mconn = Redis(host="192.168.35.110", port=6379, db=0, decode_responses=True)


def ip_to_score(ip_address):
    score = 0
    for v in ip_address.split('.'):
        score = score * 256 + int(v, 10)
    return score


def import_ips_to_redis(conn, filename):
    csv_file = csv.reader(open(filename, 'r'))
    for count, row in enumerate(csv_file):
        start_ip = row[0] if row else ''
        if 'i' in start_ip.lower():
            continue
        if '.' in start_ip:
            start_ip = ip_to_score(start_ip)
        elif start_ip.isdigit():
            start_ip = int(start_ip, 10)
        else:
            continue
        city_id = row[2] + '_' + str(count)
        conn.zadd('ip2cityid:', {city_id: start_ip})


def import_cites_to_redis(conn, filename):
    for row in csv.reader(open(filename, 'r')):
        if len(row) < 4 or not row[0].isdigit():
            continue;
        city_id = row[0]
        country = row[1]
        region = row[2]
        city = row[3]
        conn.hset('cityid2city:', city_id, json.dumps([city, region, country]))


def find_city_by_ip(conn, ip_address):
    if isinstance(ip_address, str):
        ip_address = ip_to_score(ip_address)
    city_id = conn.zrevrangebyscore('ip2cityid:', ip_address, 0, start=0, num=1)
    if not city_id:
        return None
    city_id = city_id[0].partition('_')[0]
    return json.loads(conn.hget('cityid2city:', city_id))


def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print(ip_to_score('192.168.5.108'))
    import_ips_to_redis(mconn, 'D:\ip.csv')
    import_cites_to_redis(mconn, 'D:\city.csv')
    print(find_city_by_ip(mconn, '192.168.5.103'))
    print_hi('PyCharm')

